/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.dreamsoft;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import br.com.dreamsoft.Expression.ExpressionCalc;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author rafael
 */
public class Calc extends Activity {

    private Button bt0;
    private Button bt1;
    private Button bt2;
    private Button bt3;
    private Button bt4;
    private Button bt5;
    private Button bt6;
    private Button bt7;
    private Button bt8;
    private Button bt9;
    private EditText edt;
    //operadores
    private Button soma;
    private Button sub;
    private Button mult;
    private Button div;
    private Button igual;
    private Button ponto;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        this.setTitle("Calculadora 1.0");
        super.onCreate(icicle);
        setContentView(R.layout.main);

        /*
        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
         */

        //pega os botões da tela
        this.bt0 = (Button) findViewById(R.id.num0);
        this.bt1 = (Button) findViewById(R.id.num1);
        this.bt2 = (Button) findViewById(R.id.num2);
        this.bt3 = (Button) findViewById(R.id.num3);
        this.bt4 = (Button) findViewById(R.id.num4);
        this.bt5 = (Button) findViewById(R.id.num5);
        this.bt6 = (Button) findViewById(R.id.num6);
        this.bt7 = (Button) findViewById(R.id.num7);
        this.bt8 = (Button) findViewById(R.id.num8);
        this.bt9 = (Button) findViewById(R.id.num9);
        this.ponto = (Button) findViewById(R.id.ponto);
        this.edt = (EditText) findViewById(R.id.campo);

        //pega os botoes de operadores
        this.soma = (Button) findViewById(R.id.soma);
        this.div = (Button) findViewById(R.id.div);
        this.mult = (Button) findViewById(R.id.mult);
        this.sub = (Button) findViewById(R.id.sub);

        this.igual = (Button) findViewById(R.id.igual);
        //seta os listeners
        setListeners();

    }

    private void setListeners() {
        List<Button> bts = new ArrayList<Button>();
        //preenche a lista
        bts.add(this.bt0);
        bts.add(this.bt1);
        bts.add(this.bt2);
        bts.add(this.bt3);
        bts.add(this.bt4);
        bts.add(this.bt5);
        bts.add(this.bt6);
        bts.add(this.bt7);
        bts.add(this.bt8);
        bts.add(this.bt9);
        bts.add(this.soma);
        //percorre todos os botoes e seta o listener
        for (final Button bt : bts) {
            bt.setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    edt.setText(edt.getText().toString() + bt.getText().toString());
                }
            });
        }
        //define os listeners para os operadores
        List<Button> ops = new ArrayList<Button>();
        ops.add(this.soma);
        ops.add(this.sub);
        ops.add(this.mult);
        ops.add(this.div);
        ops.add(this.ponto);
        //define os listeners para os operadores
        for (final Button op : ops) {
            op.setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    int lengthStr = edt.getText().toString().length();
                    //verifica se o campo não esta vazio e se ja não foi digitado no fim da expressão algum caractere de operação
                    if (!edt.getText().toString().equals("") && (edt.getText().toString().charAt(lengthStr - 1) != '*' && edt.getText().toString().charAt(lengthStr - 1) != '-' && edt.getText().toString().charAt(lengthStr - 1) != '+' && edt.getText().toString().charAt(lengthStr - 1) != '/' && edt.getText().toString().charAt(lengthStr - 1) != '.')) {

                        edt.setText(edt.getText().toString() + op.getText().toString());
                    }
                }
            });
        }
        //seta o listener para o botão igual
        this.igual.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                //verifica se campo não esta vazio
                if (!edt.getText().toString().equals("")) {

                    ExpressionCalc expCalc = new ExpressionCalc(edt.getText().toString());
                    try {
                        //calcula o valor da expressão e joga no editText
                        edt.setText(expCalc.calcular());
                    } catch (ArithmeticException ex) {
                        ex.printStackTrace();
                        msgErro("Erro aritmético!");
                    } catch (NumberFormatException ex) {
                        ex.printStackTrace();
                        msgErro("Valores inválidos\nErro ao converter os números!");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        msgErro("Erro no sistema!");
                    }


                }
            }
        });
    }

    private void msgErro(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog d = builder.create();
        d.setTitle("Opss, Erro!");

        d.setMessage(msg);
        d.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        d.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater infrater = getMenuInflater();
        infrater.inflate(R.menu.menu_calc, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.sair:
                this.finish();
                break;
            default:
                new AlertDialog.Builder(this).setTitle("Erro").setMessage("Não deveria entrar aqui!").show();
        }
        return true;
    }




}
